package com.justgame.project.cloud.common.util;

import com.justgame.project.cloud.common.util.HttpContextUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 设备信息获取工具
 */
@Component
public class AgentUtils {
    private static String pattern = "^Mozilla/\\d\\.\\d\\s+\\(+.+?\\)";
    private static String pattern2 = "\\(+.+?\\)";
    private static Pattern r = Pattern.compile(pattern);
    private static Pattern r2 = Pattern.compile(pattern2);

    public static String getDeviceInfo() {
        return getDeviceInfo(HttpContextUtil.getHttpRequest());
    }

    public static String getDeviceInfo(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        return getDeviceInfo(userAgent);
    }

    private static String getDeviceInfo(String userAgent) {
        Matcher m = r.matcher(userAgent);
        String result = null;
        if (m.find()) {
            result = m.group(0);
        }
        if (result == null) return "";
        Matcher m2 = r2.matcher(result);
        if (m2.find()) {
            result = m2.group(0);
        }
        result = result.replace("(", "");
        result = result.replace(")", "");
        return filterDeviceInfo(result);
    }

    public static String filterDeviceInfo(String result) {
        if (StringUtils.isBlank(result)) {
            return null;
        }
        result = result.replace(" U;", "");
        result = result.replace(" zh-cn;", "");
        return result;
    }

    public static String getPlatform() {
        return getPlatform(HttpContextUtil.getHttpRequest());
    }

    public static String getPlatform(HttpServletRequest request) {
        String plat = getDeviceInfo(request).toLowerCase();
        if (StringUtils.isBlank(plat)) {
            return "Unknown#";
        }

        if (plat.contains("windows")) {
            return "PC#";
        } else if (plat.contains("android")) {
            return "Android#";
        } else if (plat.contains("iphone") || plat.contains("ipad")) {
            return "IOS#";
        } else if (plat.endsWith("wx")) {
            return "Wechat#";
        } else {
            return plat;
        }
    }
}
